<template>
  <el-dialog :title="editdirectory.id ? '修改目录' : '新增目录'" :visible.sync="dialogVisible" :before-close="close">
  <el-form :model="editdirectory" ref="formName" :rules="rules">
     <el-form-item label="学科选择" v-if="!$route.query.id" prop="subjectID">
      <el-select v-model="editdirectory.subjectID" placeholder="请选择学科" >
        <el-option v-for="item in subjectList" :key="item.id" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="目录名称" prop="directoryName">
      <el-input v-model="editdirectory.directoryName" placeholder="请输入"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="close">取消</el-button>
    <el-button @click="addDirectory(form)" type="primary">确定</el-button>
  </div>
</el-dialog>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/directorys.js'
export default {
  name: 'directorysAdd',
  props: ['dialogVisible', 'editdirectory'],
  data () {
    return {
      rules: {
        subjectID: [
          { type: 'number', message: '请选择所属学科', tirgger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名字', tigger: 'blur' }
        ]
      },
      subjectList: [], // 学科列表
      form: {}
    }
  },
  created () {
    // 获取学科列表
    this.getSubject()
  },
  methods: {
    // 获取学科列表的方法
    async getSubject () {
      const result = await simple()
      // console.log(result)
      this.subjectList = result.data
    },
    // 添加方法,进行添加或者编辑的判断,条件是父组件是否传值
    addDirectory () {
      this.$refs.formName.validate(async (valid) => {
        if (valid) {
          this.form = this.editdirectory
          console.log(this.form)
          if (this.editdirectory.id) {
            await update(this.form)
            this.$message.success('更新成功')
            this.close()
            this.$emit('refresh')
          } else {
            await add(this.form)
            this.$message.success('添加成功')
            this.close()
            this.$emit('refresh')
          }
        }
      })
    },
    // 清除方法
    close () {
      this.$emit('closeDia')
      this.form.directoryName = ''
      this.form.subjectID = null
    }
  }
}
</script>

<style scoped lang='less'></style>
